﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Text.RegularExpressions;
using DNA.Mvc.Text;

namespace DNA.Mvc.Community.Events
{
    public class DeletePostEventObserver:TemplatedMailEventObserver<DeletePostEvent>
    {
        private readonly Regex DeleteByRegex = new Regex("\\{deleteby\\}", RegexOptions.Compiled);
        private readonly Regex ForumRegex = new Regex("\\{forum\\}", RegexOptions.Compiled);
        private readonly Regex SubjectRegex = new Regex("\\{subject\\}", RegexOptions.Compiled);
        private readonly Regex SummaryRegex = new Regex("\\{summary\\}", RegexOptions.Compiled);
        private readonly Regex ReasonRegex = new Regex("\\{reason\\}", RegexOptions.Compiled);

        protected override string GetDestinationAddress(DeletePostEvent e)
        {
            var user = Membership.GetUser(e.Post.UserName);
            if (user != null)
                return user.Email;
            return "";
        }

        string body = "";

        protected override void OnFormatHtmlBody(DeletePostEvent e, ref string html)
        {
            var user = Membership.GetUser(e.Post.DeleteBy);
            html = DeleteByRegex.Replace(html, user.GetDisplayName());
            html = ForumRegex.Replace(html, e.Post.Thread.Forum.Title);
            html = SubjectRegex.Replace(html, e.Post.Title);
            string summary = TextEngine.BBCode(e.Post.Body).ToHtmlString();
            html = SummaryRegex.Replace(html, summary);
            html = ReasonRegex.Replace(html, e.Post.DeletedReason);
            body = html;
        }

        protected override void OnFormatTextBody(DeletePostEvent e, ref string text)
        {
            var sb = new StringBuilder();
            sb.AppendFormat("Your post {0} - {1}", e.Post.Title, e.Post.Thread.Forum.Title)
                .AppendLine()
                .AppendLine(TextEngine.BBCode(e.Post.Body).ToHtmlString())
                .AppendFormat("Has been deleted by {1}",Membership.GetUser(e.Post.DeleteBy).GetDisplayName())
                .AppendLine() 
                .AppendLine("The delete reason is:")
                .AppendLine(e.Post.DeletedReason);
            text = sb.ToString();
        }

        
    }
}
